package org.kunlong.qgen.common.util;

import java.io.File;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.kunlong.qgen.boot.Boot;
import org.kunlong.qgen.domain.Template;
import org.kunlong.qgen.domain.TemplateHolder;

public final class TemplateManager {
	private static final String FONT_SIZE_TAG = "FontSize";
	private static final String NAME_ATTR = "name";
	private static final String TEMPLATE_TAG = "Template";
	private static final String TEMPLATE_DEFAULT_LOCATION = Boot.CURRENT_DIRECTORY
			+ "/template/template.xml";
	private static TemplateHolder templateHolder=new TemplateHolder();

	private TemplateManager() {
		// TODO Auto-generated constructor stub
	}
	
	public static void loadTemplate() throws Exception {
		loadTemplate(TEMPLATE_DEFAULT_LOCATION);
	}
	
	@SuppressWarnings("unchecked")
	public static void loadTemplate(String templateFilePath) throws Exception {
		File file = new File(templateFilePath);
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(file);
		Element templatesRoot = document.getRootElement();
		List<Element> templateList = templatesRoot.elements(TEMPLATE_TAG);
		for (Element e : templateList) {
			Template template = new Template();
			String templateName = e.attribute(NAME_ATTR).getText();
			template.setName(templateName);
			Element fontElement = e.element(FONT_SIZE_TAG);
			if (fontElement != null) {
				String fontSize = fontElement.getText();
				try {
					template.setFontSize(Integer.parseInt(fontSize));
				} catch (Exception ex) {
					template.setFontSize(Template.DEFAULT_FONT_SIZE);
				}
			} else {
				template.setFontSize(Template.DEFAULT_FONT_SIZE);
			}
			templateHolder.getTemplateMap().put(templateName, template);
			System.out.println("Loading Template:" + templateName);
		}
	}

	public static TemplateHolder getTemplateHolder() {
		return templateHolder;
	}

	public static void setTemplateHolder(TemplateHolder templateHolder) {
		TemplateManager.templateHolder = templateHolder;
	}
}
